<?php
namespace Home\Controller;
use Home\Controller\BaseController;
use Think\Page;
class MemberController extends BaseController{

	public function __construct(){

		parent::__construct();
		$this->mod = D('Member');
		$this->commentMod = D('Comment');
		$this->articleMod = D('Article');
		$this->followMod = D('Follow');
		$this->art_classMod = D('ArticleClass');
//        $this->pdMod = D('pd_log');
        $this->predepositMod =new \Home\Model\PredepositModel('pd');
		$this->art_class = $this->art_classMod->order('ac_sort')->select();
		$this->pageNum = 10;
	}

    //充值明细
    public function pd_recharge(){
        $condition = array();
        $condition['pdr_member_id']	= $_SESSION['member_id'];
        if (!empty($_GET['pdr_sn'])) {
            $condition['pdr_sn'] = $_GET['pdr_sn'];
        }
        $count = $this->predepositMod->table(C('DB_PREFIX')."pd_recharge")->where($condition)->count();
        $page = new Page($count,$this->pageNum);
        $list = $this->predepositMod->getPdRechargeList($condition,'*','pdr_id desc',$page->firstRow.','.$page->listRows);

        $this->assign('list',$list);
        $this->assign('page',$page->show());
        $this->assign('localTitle','充值明细');
        $this->display();
    }

    //提现明细列表
    public function pd_cash_list(){
        $condition = array();
        $condition['pdc_member_id'] =  $_SESSION['member_id'];
        if (!empty($_GET['sn_search'])) {
            $condition['pdc_sn'] = $_GET['sn_search'];
        }
        if (isset($_GET['paystate_search'])){
            $condition['pdc_payment_state'] = intval($_GET['paystate_search']);
        }
        $count = $this->predepositMod->table(C('DB_PREFIX')."pd_cash")->where($condition)->count();
        $page = new Page($count,$this->pageNum);
        $list = $this->predepositMod->getPdCashList($condition,'*','pdc_id desc',$page->firstRow.','.$page->listRows);

        $this->assign('list',$list);
        $this->assign('page',$page->show());
        $this->assign('localTitle','余额提现');
        $this->display();
    }

    //充值添加表单页面
    public function pd_recharge_add(){
        if(IS_POST){
            $this->assign('localTitle','充值余额');
            $this->display();
            exit();
        }
        $pdr_amount = abs(floatval($_POST['pdr_amount']));
//        if ($pdr_amount <= 0) {
//            showMessage('充值金额为大于或者等于0.01的数字','','html','error');
//        }
        $data = array();
        $data['pdr_sn'] = $pay_sn = $this->predepositMod->makeSn();
        $data['pdr_member_id'] = $_SESSION['member_id'];
        $data['pdr_member_name'] = $_SESSION['member_name'];
        $data['pdr_amount'] = $pdr_amount;
        $data['pdr_add_time'] = NOW_TIME;

        $payment_api=new \Common\Lib\Alipay\Alipay();
        @header("Location: ".$payment_api->toAlipay(array()));

//        $insert = $model_pdr->addPdRecharge($data);
//        if ($insert) {
            //转向到商城支付页面
//            redirect('index.php?act=buy&op=pd_pay&pay_sn='.$pay_sn);
//        }
    }

    //查看充值详情
    public function pd_recharge_view(){
        $pdr_id = intval($_GET["id"]);
        if ($pdr_id <= 0){
            showMessage('参数错误','','html','error');
        }
        $condition = array();
        $condition['pdr_member_id'] = $_SESSION['member_id'];
        $condition['pdr_id'] = $pdr_id;
        $condition['pdr_payment_state'] = 1;
        $info = $this->predepositMod->getPdRechargeInfo($condition);
        if (!$info){
            showMessage('记录信息错误','','html','error');
        }
        $this->assign('info',$info);
        $this->assign('localTitle','充值详情');
        $this->display();
    }

    //余额提现邮箱或是短信验证页面
    public function pd_cash_auth(){

        if (IS_POST) {
//            if (!in_array($_POST['type'],array('modify_pwd','modify_mobile','modify_email','modify_paypwd','pd_cash'))) {
//                redirect(U('index'));  //返回用户中心
//            }
            $member_common_info = M('member')->where(array('member_id'=>session('member_id')))->find();
            if (empty($member_common_info) || !is_array($member_common_info)) {
                showMessage('验证失败','','html','error');
            }
            if ($member_common_info['auth_code'] != $_POST['auth_code'] || NOW_TIME - $member_common_info['send_acode_time'] > 1800) {
                showMessage('验证码已被使用或超时，请重新获取验证码','','html','error');
            }
            $data = array();
            $data['auth_code'] = '';
            $data['send_acode_time'] = 0;
            $update = M('member')->where(array('member_id'=>session('member_id')))->save($data);
            if (!$update) {
                showMessage('系统发生错误，如有疑问请与管理员联系','','html','error');
            }

            $this->display('pd_cash_auth');

        } else {
//            if (!in_array($_GET['type'],array('modify_pwd','modify_mobile','modify_email','modify_paypwd','pd_cash'))) {
//                redirect('index.php?act=member_security&op=index');
//            }
            $member_info = M('member')->where(array('member_id'=>session('member_id')))->find();
            //第一次绑定邮箱，不用发验证码，直接进下一步
            //第一次绑定手机，不用发验证码，直接进下一步
            if ($member_info['mobile']==null ||$member_info['mobile'] == '') {
                redirect(U('pd_cash_list_add'));
            }
            $this->assign('localTitle','申请提现');
            $this->assign('member_info',$member_info);
            $this->display('pd_cash_auth');

        }
    }

    //余额提现申请表单页面
    public function pd_cash_list_add(){
        $this->assign('localTitle','申请提现');
        $member_info = M('member')->where(array('member_id'=>session('member_id')))->find();
        $this->assign('member_info',$member_info);
        $this->display();
    }

    //查看提现详情
    public function pd_cash_list_view(){
        $pdc_id = intval($_GET["id"]);
        if ($pdc_id <= 0){
            showMessage('参数错误','','html','error');
        }
        $condition = array();
        $condition['pdc_member_id'] = $_SESSION['member_id'];
        $condition['pdc_id'] = $pdc_id;
        $info = $this->predepositMod->getPdCashInfo($condition);
        if (empty($info)){
            showMessage('记录信息错误','','html','error');
        }

        $this->assign('info',$info);
        $this->assign('localTitle','提现详情');
        $this->display();
    }


    //账户余额
    public function myaccount(){
        $condition = array();
        $condition['lg_member_id'] = $_SESSION['member_id'];
        $count = $this->predepositMod->table(C('DB_PREFIX')."pd")->where($condition)->count();
        $page = new Page($count,$this->pageNum);
        $list = $this->predepositMod->getPdLogList($condition,'*','lg_id desc',$page->firstRow.','.$page->listRows);

        //信息输出
        $this->assign('list',$list);
        $this->assign('page',$page->show());
        $this->assign('localTitle','账户余额');
        $this->display();


    }

	/**
	 * 个人中心(编辑资料)
	 */
	public function index(){
		if (IS_POST) {
			$data = array();
			if (!empty($_POST['nickname'])) {
				$data['nickname'] = str_rp(trimall($_POST['nickname']));
			}
			if (!empty($_POST['introduce'])) {
				$data['introduce'] = str_rp(trim($_POST['introduce']));
			}
			if (!empty($_POST['password'])) {
				$pwd = $this->mod->where(array('member_id'=>$this->mid))->getField('pwd');
				if ($pwd != $_POST['password']) {
					$data['pwd'] = re_md5($_POST['password']);
				}
			}
			if (!empty($_POST['profession'])) {
				$data['profession'] = str_rp(trimall($_POST['profession']));;
			}
			//图片上传
			if(!empty($_FILES['file']['size']))
			{
				$arc_img = 'avatar_'.$this->mid;
				$param = array('savePath'=>'member/avatar/','subName'=>'','files'=>$_FILES['file'],'saveName'=>$arc_img,'saveExt'=>'');
				$up_return = upload_one($param);
				if($up_return == 'error')
				{
					$this->error('图片上传失败');
					exit;
				}else{
					$data['avatar'] = $up_return;
				}
			}
			if (!empty($data) && $this->mid) {
				$res = $this->mod->where(array('member_id'=>$this->mid))->save($data);
				if ($res) {
					$this->success('编辑个人资料成功');
				}else {
					$this->error('编辑个人资料失败');
				}
			}
		}elseif (IS_GET) {
			$this->check_login();
			$this->display();
		}
	}
	public function myJoin(){
		$where['member_id'] = $this->mid;
		$order = 'addtime desc';
		$count = $this->commentMod->where($where)->count();
		$page = new Page($count,$this->pageNum);
		$list = $this->commentMod->where($where)->limit($page->firstRow.','.$page->listRows)->order($order)->select();
		$this->assign('page',$page->show());
		$this->assign('list',$list);
		$this->assign('localTitle','我参与的');
		$this->display('mylist');
	}
	public function delComment(){
		$id = intval($_GET['id']);
		$where['id'] = $id;
		$where['member_id'] = $this->mid;
		$res = $this->commentMod->where($where)->delete();
		if ($res) {
			$this->success('删除成功');
		}else {
			$this->error('删除失败');
		}
	}
	public function hosting(){
		if (IS_POST) {
			$id = intval($_POST['article_id']);
            $data['mode'] = intval($_POST['mode_id']);
			$data['ac_id'] = intval($_POST['ac_id']);
			$ac = $this->art_classMod->where(array('ac_id'=>$data['ac_id']))->find();
			$data['article_title'] = str_rp(trim($_POST['article_title']));
			$data['article_content'] = str_rp(trim($_POST['article_content']));
			$data['article_key'] = $data['article_title'].','.$ac['ac_name'].','.$ac['ac_key'];
			$data['article_desc'] = $data['article_content'];
			$data['article_show'] = 1;
			$data['article_sort'] = 10;
			$data['article_time'] = NOW_TIME;
			$data['member_id'] = $this->mid;
            $path=RUNTIME_PATH.'Exts/keyword.php';
            $keyword_data= include($path);
            //屏蔽污秽词语
            foreach($keyword_data as $key=>$value){
                $content_length=mb_strlen($value,'UTF8');
                $replace_str="";
                for($i=0;$i<$content_length;$i++){
                    $replace_str.="*";
                }
                $data['article_title']=preg_replace('/'.$value.'/',$replace_str,$data['article_title'],-1);
                $data['article_content']=preg_replace('/'.$value.'/',$replace_str,$data['article_content'],-1);
            }
			if ($id) {
				$res = $this->articleMod->where(array('article_id'=>$id,'member_id'=>$this->mid))->save($data);
			}else {
				$res = $this->articleMod->add($data);
			}
			if ($res){
				$this->success('发布成功');
			}else {
				$this->error('发布失败');
			}
		}else {
			$id = intval($_GET['id']);
			$info = $this->articleMod->where(array('article_id'=>$id,'member_id'=>$this->mid))->find();
			$this->vip_level = $this->mod->where(array('member_id'=>$this->mid))->getField('vip_level');

			if (!empty($info)) {
                $this->assign('info',$info);
            }
			$this->display();
		}
	}
	public function rewrite(){
		if (IS_POST) {
			$where['id'] = intval($_POST['id']);
			$where['member_id'] = $this->mid;
			$data['content'] = str_rp(trim($_POST['content']));
			$data['addtime'] = NOW_TIME;
			$res = $this->commentMod->where($where)->save($data);
			if ($res) {
				$this->success('编辑成功');
			}else {
				$this->error('编辑失败');
			}
		}elseif (IS_GET) {
			$where['id'] = intval($_GET['id']);
			$where['member_id'] = $this->mid;
			$info = $this->commentMod->where($where)->find();
			$this->assign('info',$info);
			$this->display();
		}
	}
	public function myHost(){
		$where['member_id'] = $this->mid;
		$order = 'article_time desc';
		$count = $this->articleMod->where($where)->count();
		$page = new Page($count,$this->pageNum);
		$list = $this->articleMod->where($where)->limit($page->firstRow.','.$page->listRows)->order($order)->select();
		$this->assign('list',$list);
		$this->assign('page',$page->show());
		$this->assign('localTitle','我的论点');
		$this->display();
	}
	public function invited(){
		$where['member_id'] = $this->mid;
		$where['follow_type'] = 'Invitation';
		$invited_list = $this->followMod->where($where)->select();

		if (!empty($invited_list)) {
			$art_class_ids = '';
			foreach ($invited_list as $key => $val){
				$art_class_ids .= $val['follow_id'].',';
			}

			$art_class_ids = substr($art_class_ids, 0, -1);
			unset($where);
			$where['article_id'] = array('IN',$art_class_ids);
			$order = 'article_time desc';
			$count = $this->articleMod->where($where)->count();
			$page = new Page($count,$this->pageNum);
			$list = $this->articleMod->where($where)->limit($page->firstRow.','.$page->listRows)->order($order)->select();
			$this->assign('list',$list);
			$this->assign('page',$page->show());
		}
		$this->assign('localTitle','邀请我的');
		$this->display();
	}
	public function delInvited(){
		$where['follow_id'] = intval($_GET['id']);
		$where['member_id'] = $this->mid;
		$res = $this->followMod->where($where)->delete();
		if ($res) {
			$this->success('拒绝邀请成功');
		}else {
			$this->error('拒绝邀请失败');
		}
	}
	public function delArticle(){
		$where['article_id'] = intval($_GET['id']);
		$where['member_id'] = $this->mid;
		$res = $this->articleMod->where($where)->delete();
		if ($res) {
			$this->commentMod->where(array('article_id'=>$where['article_id']))->delete();
			$this->success('删除论题成功');
		}else {
			$this->error('删除论题失败');
		}
	}
	public function myFollow(){
		$where['member_id'] = $this->mid;
		$where['follow_type'] = 'Comment';
		$count = $this->followMod->relation('Comment')->where($where)->count();
		$page = new Page($count,$this->pageNum);
		$list = $this->followMod->relation('Comment')->where($where)->limit($page->firstRow.','.$page->listRows)->select();
		$this->assign('list',$list);
		$this->assign('page',$page->show());
		$this->assign('localTitle','我的关注');
		$this->display();
	}
	public function delFollow(){
		$where['follow_id'] = intval($_GET['id']);
		$where['member_id'] = $this->mid;
		$where['follow_type'] = 'Comment';
		$res = $this->followMod->where($where)->delete();
		if ($res) {
			$this->success('取消关注成功');
		}else {
			$this->error('取消关注失败');
		}
	}
	/**
	 * 登出
	 */
	public function logout(){
		session('member_id',null);
		$this->success("退出成功！",C('SiteUrl'));
		exit;
	}

    /*-----------------------------------------------------------------------------------------------------------------------*/



    /**
     * 统一发送身份验证码
     */
    public function send_auth_code() {
        if (!in_array($_GET['type'],array('email','mobile'))) exit();

        $model_member = Model('member');
        $member_info = $model_member->getMemberInfoByID($_SESSION['member_id'],'member_email,member_mobile');

        $verify_code = rand(100,999).rand(100,999);
        $data = array();
        $data['auth_code'] = $verify_code;
        $data['send_acode_time'] = NOW_TIME;
        $update = $model_member->editMemberCommon($data,array('member_id'=>$_SESSION['member_id']));
        if (!$update) {
            exit(json_encode(array('state'=>'false','msg'=>'系统发生错误，如有疑问请与管理员联系')));
        }

        $model_tpl = Model('mail_templates');
        $tpl_info = $model_tpl->getTplInfo(array('code'=>'authenticate'));

        $param = array();
        $param['send_time'] = date('Y-m-d H:i',TIMESTAMP);
        $param['verify_code'] = $verify_code;
        $param['site_name']	= C('site_name');
        $subject = ncReplaceText($tpl_info['title'],$param);
        $message = ncReplaceText($tpl_info['content'],$param);
        if ($_GET['type'] == 'email') {
            $email	= new Email();
            $result	= $email->send_sys_email($member_info["member_email"],$subject,$message);
        } elseif ($_GET['type'] == 'mobile') {
            $sms = new Sms();
            $result = $sms->send($member_info["member_mobile"],$message);
        }
        if ($result) {
            exit(json_encode(array('state'=>'true','msg'=>'验证码已发出，请注意查收')));
        } else {
            exit(json_encode(array('state'=>'false','msg'=>'验证码发送失败')));
        }
    }
}